package by.koleda.photoupdater.service;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.util.Log;
import by.koleda.photoupdater.manager.ContactsManager;
import by.koleda.photoupdater.model.Contact;
import by.koleda.photoupdater.provider.PhotoContract;
import by.koleda.photoupdater.provider.PhotoContract.Suggestions;

public class MakeSuggestionsService extends Service {
	
	public static final String EXTRA_KEY_MESSAGE = "message";
	
	public static final String ACTION_ON_ERROR = "by.koleda.photoupdater.service.MAKE_SUGGESTIONS_SERVICE_ACTION_ON_ERROR";
	
	public static final String ACTION_ON_SUCCESS = "by.koleda.photoupdater.service.MAKE_SUGGESTIONS_SERVICE_ACTION_ON_SUCCESS";
		
	public static final String TAG = MakeSuggestionsService.class.getSimpleName();
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handleCommand(intent);
		return START_STICKY;
	}

	protected void handleCommand(Intent intent) {
		if (intent == null) {
			return;
		}
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				Context context = MakeSuggestionsService.this;
				
				context.getContentResolver().delete(PhotoContract.Suggestions.CONTENT_URI, PhotoContract.Suggestions.VKLINKED + " <> 1 ", null);
				
				ArrayList<Contact> contactList = ContactsManager.getContactList(MakeSuggestionsService.this);
				ArrayList<String> linkedContacts = ContactsManager.getLinked(MakeSuggestionsService.this);
				ArrayList<Long> vkLinked = ContactsManager.getVkLinked(MakeSuggestionsService.this);
				HashMap<String,Long> vkMobilePhone = ContactsManager.getVkMobilePhone(MakeSuggestionsService.this);
				HashMap<String, ArrayList<Long>> vkFirstName = ContactsManager.getVkFirstName(MakeSuggestionsService.this);
				HashMap<String, ArrayList<Long>> vkLastName = ContactsManager.getVkLastName(MakeSuggestionsService.this);
				
				for (Contact contact: contactList) {
					if (linkedContacts.contains(contact.getContactId())) {
						continue;
					}
					
					Long uid = null;
					ArrayList<Long> firstNameUids = null;
					ArrayList<Long> lastNameUids = null;
					HashMap<Long, Integer> possibleUids = new HashMap<Long, Integer>();
					try {
						if (vkMobilePhone.containsKey(contact.getPhoneNumber())) {
							uid = vkMobilePhone.get(contact.getPhoneNumber());
						}
						if (vkFirstName.containsKey(contact.getFirstName())) {
							firstNameUids = vkFirstName.get(contact.getFirstName());
						}
						if (vkLastName.containsKey(contact.getLastName())) {
							lastNameUids = vkLastName.get(contact.getLastName());
						}
						
						if (uid != null) {
							possibleUids.put(uid, 3);
						}
						if (firstNameUids != null) {
							for (Long firstNameUid: firstNameUids) {
								if (possibleUids.containsKey(firstNameUid)) {
									possibleUids.put(firstNameUid, possibleUids.get(firstNameUid) + 1);
								} else {
									possibleUids.put(firstNameUid, 1);
								}
							}
						}
						
						if (lastNameUids != null) {
							for (Long lastNameUid: lastNameUids) {
								if (possibleUids.containsKey(lastNameUid)) {
									possibleUids.put(lastNameUid, possibleUids.get(lastNameUid) + 2);
								} else {
									possibleUids.put(lastNameUid, 2);
								}
							}
						}
						
						if (!possibleUids.isEmpty()) {
								for (Long possibleUid: possibleUids.keySet()) {
									if (vkLinked.contains(possibleUid)) {
										continue;
									}
									ContentValues contentValues = new ContentValues();
									contentValues.put(Suggestions.CONTACT_ID, contact.getContactId());
									contentValues.put(Suggestions.VKCONTACT_ID, possibleUid);
									contentValues.put(Suggestions.VKLINKED, Boolean.FALSE);
									contentValues.put(Suggestions.VKPOINTS, possibleUids.get(possibleUid));
									
									Cursor cursor = context.getContentResolver().query(PhotoContract.Suggestions.CONTENT_URI, null, PhotoContract.Suggestions.CONTACT_ID + " = " + contact.getContactId() + " AND " + PhotoContract.Suggestions.VKCONTACT_ID + " = " + possibleUid, null, null);
									if (cursor.moveToFirst()) {
										int idIndex = cursor.getColumnIndexOrThrow(PhotoContract.Suggestions._ID);
										int suggestionId = cursor.getInt(idIndex);
										context.getContentResolver().update(PhotoContract.Suggestions.buildSuggestionUri(String.valueOf(suggestionId)), contentValues, null, null);
									} else {
										context.getContentResolver().insert(PhotoContract.Suggestions.CONTENT_URI, contentValues);
									}
									cursor.close();
									
									Intent intent = new Intent(ACTION_ON_SUCCESS);
									sendBroadcast(intent);
								}
							}
						} catch (Exception e) {
							Log.e(TAG, e.getMessage());
							Intent intent = new Intent(ACTION_ON_ERROR);
							sendBroadcast(intent);
					}
				}
			}
		}).start();
		
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

}
